package cn.shenlong.portal.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.shenlong.common.Page;
import cn.shenlong.domain.TreeNode;
import cn.shenlong.portal.domain.Company;
import cn.shenlong.portal.domain.Icon;
import cn.shenlong.portal.domain.Store;
import cn.shenlong.portal.domain.Store2tag;
import cn.shenlong.portal.domain.StoreBO;
import cn.shenlong.portal.domain.Storetag;
import cn.shenlong.portal.service.CompanyService;
import cn.shenlong.portal.service.IconService;
import cn.shenlong.portal.service.StoreService;
import cn.shenlong.portal.service.StoretagService;

/**
 * 商品管理
 * @author 
 *
 * 2014-4-1
 */
@Controller
@RequestMapping("/store/admin")
public class StoreAController {

	@Autowired
	private StoreService storeService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private IconService iconService;
	@Autowired
	private StoretagService storetagService;
	
	/**
	 * 商家列表
	 * @param searchProperty 搜索参数名
	 * @param searchValue    搜索值
	 * @param pageNo
	 * @param pageSize
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(String searchProperty, String searchValue,Integer pageNumber, Integer pageSize,
			HttpServletRequest request, ModelMap model) {
		if (pageNumber == null) {
			pageNumber = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		Map<String, Object> para = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(searchValue)) {
            model.addAttribute("searchProperty", searchProperty);
            model.addAttribute("searchValue", searchValue);
            if(StringUtils.isNotBlank(searchProperty)){
            	if(searchProperty.equals("companyName")){
            		para.put("companyName",searchValue);
            	}
            	if(searchProperty.equals("address")){
            		para.put("address",searchValue);
            	}
            }
        }		
        Page<StoreBO> p = storeService.findPageListBOByCriteria(pageNumber, pageSize,para);
		model.put("page", p);
		return "/server/store/list";
	}
	
	/**
	 * 编辑商家信息
	 * @param storeId 商家ID
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/editStore")
	public String editStore(Long storeId,ModelMap model){
		if(storeId!=null && storeId>0){
			Store store = storeService.findByPK(storeId);
			Company company = this.companyService.findCompanyByCompanyId(store.getCompanyId());
			List<Icon> icons = (List<Icon>) iconService.findIcon(null, null, null, null).getList();
			List<Store2tag> mytag=storetagService.findStore2tagByStoreId(storeId.intValue());
			if(mytag!=null && mytag.size()>0){
				StringBuffer nameBuffer=new StringBuffer();
				StringBuffer idBuffer=new StringBuffer();
				for (Store2tag store2tag : mytag) {
					Storetag tag = storetagService.findStoretagById(store2tag.getTagId());
					nameBuffer.append(tag.getTagName()).append(",");
					idBuffer.append(tag.getId()).append(",");
				}
				model.put("tagName", nameBuffer.subSequence(0, nameBuffer.lastIndexOf(",")).toString());//标签信息
				model.put("tagIds", idBuffer.subSequence(0, idBuffer.lastIndexOf(",")).toString());
			}
			model.put("storeId", storeId);
			model.put("store", store);
			model.put("company", company);
			model.put("icons", icons);
			model.put("mytag", mytag);
			return "/server/store/edit";
		}else{
			model.addAttribute("errorMsg", "商家ID传递参数错误!");
			return "/common/error";
		}
	}
	
    /**
     * 跳转标签选择页面
     * @param model
     * @return
     */
    @RequestMapping("/getTags")
    public String getTags(ModelMap model,Long storeId) {
    	model.addAttribute("storeId", storeId);
        return "/server/store/tags_tree";
    }
    
    /**
     * 获取标签数据
     * @return
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("/getTagsTree")
    @ResponseBody
    public List<TreeNode<Long>> getTagsTree(ModelMap model,Long storeId){
    	List<TreeNode<Long>> treeList = new ArrayList<TreeNode<Long>>();
		Page<Storetag> page=storetagService.findForStoretag(null, null, null);//所有标签数据
		List<Storetag> tags=(List<Storetag>) page.getList();
    	TreeNode<Long> treeFirst = new TreeNode<Long>();
        treeFirst.setId(-22l);
        treeFirst.setpId(-3l);
        treeFirst.setName("标签");
        treeFirst.setOpen(true);
        treeList.add(treeFirst);
        if(tags!=null && tags.size()>0){
        	List<Store2tag> mytag=storetagService.findStore2tagByStoreId(storeId.intValue());//商家已使用标签
        	for (Storetag tag : tags) {
        		TreeNode<Long> treeNo = new TreeNode<Long>();
        		String name=tag.getTagName();
        		if(mytag!=null && mytag.size()>0){
        			for (Store2tag store2tag : mytag) {
        				if(store2tag.getTagId().equals(tag.getId())){
        					name=name+"&nbsp;&nbsp;[<span style='color:red;margin-right:0px;'>"+"已选择"+"</span>]";
        					treeNo.addAttributes("type", "1");
        				}
        			}
        		}
                treeNo.setId(Long.valueOf(tag.getId()));
                treeNo.setpId(-22l);
                treeNo.setName(name);
                treeNo.setOpen(true);
                treeList.add(treeNo);
			}
        }
        return treeList;
    }
    
    /**
     * 保存数据 
     * @param store 商家信息
     * @param company 公司信息
     * @param tagIds 标签信息
     * @param model
     * @return
     */
	@RequestMapping("/save")
	public String save(Store store,Company company,String tagIds,ModelMap model ){
		//处理商家标签信息
		storetagService.deleteStore2TagByStoreId(new Integer[]{store.getStoreId()});
		if(StringUtils.isNotBlank(tagIds)){
			String[] ids = tagIds.split(",");
			for (String tagId : ids) {
				if(tagId!=null && !"".equals(tagId)){
					Store2tag tag2 = new Store2tag();
					tag2.setStroreId(store.getStoreId());
					tag2.setTagId(Integer.valueOf(tagId));
					tag2.setDataflg(1);
					storetagService.saveStoreTag2(tag2);
				}
			}
		}
		storeService.updateEntity(store);
		companyService.updateCompany(company);
		return "redirect:list.html";
	}
	
	/**
	 * 查看商家信息
	 * @param storeId 商家ID
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/seedStore")
	public String seedStore(Long storeId,ModelMap model){
		if(storeId!=null && storeId>0){
			Store store = storeService.findByPK(storeId);
			Company company = this.companyService.findCompanyByCompanyId(store.getCompanyId());
			List<Icon> icons = (List<Icon>) iconService.findIcon(null, null, null, null).getList();
			List<Store2tag> mytag=storetagService.findStore2tagByStoreId(storeId.intValue());
			if(mytag!=null && mytag.size()>0){
				StringBuffer nameBuffer=new StringBuffer();
				StringBuffer idBuffer=new StringBuffer();
				for (Store2tag store2tag : mytag) {
					Storetag tag = storetagService.findStoretagById(store2tag.getTagId());
					nameBuffer.append(tag.getTagName()).append(",");
					idBuffer.append(tag.getId()).append(",");
				}
				model.put("tagName", nameBuffer.subSequence(0, nameBuffer.lastIndexOf(",")).toString());//标签信息
				model.put("tagIds", idBuffer.subSequence(0, idBuffer.lastIndexOf(",")).toString());
			}
			if(store!=null && store.getIconId()!=null){
				Icon icon = iconService.findIconByIconId(store.getIconId());
				model.put("icon", icon);
			}
			model.put("storeId", storeId);
			model.put("store", store);
			model.put("company", company);
			model.put("icons", icons);
			model.put("mytag", mytag);
			return "/server/store/show";
		}else{
			model.addAttribute("errorMsg", "商家ID传递参数错误!");
			return "/common/error";
		}
	}
}
